//
//  UserAccount.swift
//  sinaWeibo
//
//  Created by LSY on 15/12/17.
//  Copyright © 2015年 lsy. All rights reserved.
//

import UIKit



class UserAccount: NSObject,NSCoding {
    
    
    var access_token :String?
    
    var expires_in : NSTimeInterval = 0{
    
        didSet{
//           过期时间
        expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    
    //    token 的有效日期
    var expires_date: NSDate?
    var uid : String?
    var name :String?
    var avatar_large:String?

   
//   初始化方法
    init (dic:[String:AnyObject]){
        
        super.init()
        
        setValuesForKeysWithDictionary(dic)
        
       }
//    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
//        super.setValue(value, forUndefinedKey: key)
    }

    
    override var description:String{
    
 let key = ["access_token","expires_in","uid","name","avatar_large"]
    
        return dictionaryWithValuesForKeys(key).description
    }
    
//    保存到沙盒中
    func saveAccount (){
    
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as String).stringByAppendingString("account.plist")
        
//
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    
    }
    
//定义一个类方法，使用直接使用类
//  返回值为UserAccount
  class  func loadAccount() -> UserAccount? {
//    获取路径
    let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as String).stringByAppendingString("account.plist")
//    读取数据
    
    if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccount{
        
//        判断是否时间已经过期
        if  account.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
            
            return account
        }
    
    }
    
//需要返回一个UserAccount的对象，因为是可选项所以可以返回nil
   return nil
        
    }
    
//    归档
    required init?(coder aDecoder: NSCoder){
    
        access_token = aDecoder.decodeObjectForKey("access_token") as?String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        uid = aDecoder.decodeObjectForKey("uid") as?String
        name = aDecoder.decodeObjectForKey("name")as?String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large")as?String
    expires_date = aDecoder.decodeObjectForKey("expires_date") as?NSDate
    
    }
    
//    解归档
    func encodeWithCoder(acoder:NSCoder){
    
    acoder.encodeObject(access_token, forKey: "access_token")
        acoder.encodeDouble(expires_in, forKey: "expires_in")

        acoder.encodeObject(uid, forKey: "uid")

        acoder.encodeObject(name, forKey: "name")
        acoder.encodeObject(avatar_large, forKey: "avatar_large")
        acoder.encodeObject(expires_date, forKey: "expires_date")
    }
}
